/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ie.tcd.cs.railtickets.server.graph;

import ie.tcd.cs.railtickets.commons.util.FileUtil;
import ie.tcd.cs.railtickets.server.service.GraphService;
import ie.tcd.cs.railtickets.server.dao.DAOFactory;
import ie.tcd.cs.railtickets.server.dao.StationDAO;
import ie.tcd.cs.railtickets.server.dao.TravelPathDAO;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultDirectedWeightedGraph;
import org.jgrapht.graph.DefaultEdge;

/**
 *
 * @author Wenbo Sun
 */
public class RailsGraph implements GraphService {

    private static Graph<String, DefaultEdge> railsGraph;
    private static String GRAPHNAME = "config/rails.jgrapht";
    private static final Log log = LogFactory.getLog(RailsGraph.class);

    public RailsGraph() {
//        if (railsGraph == null) {
//            if (this.checkExist()) {
//                this.loadGraph();
//            } else {
                railsGraph = new DefaultDirectedWeightedGraph<String, DefaultEdge>(DefaultEdge.class);
                fixGraph();
//                saveGraph();
//            }
//        }
    }

    private void fixGraph() {
        TravelPathDAO tpDAO = DAOFactory.createTravelPathDAO();
        StationDAO sDAO = DAOFactory.createStationDAO();
        List edges = tpDAO.getUniquePaths();
        List<String> vertexes = sDAO.findAllNames();
        for (String vertex : vertexes) {
            railsGraph.addVertex(vertex);
        }
        for (Object o : edges) {
            Object[] ss = (Object[]) o;
            railsGraph.addEdge((String) ss[0], (String) ss[1]);
            log.debug((String) ss[0] + " -> " + ss[1]);
        }

    }

    public void saveGraph() {
        try {
            FileUtil.saveObject(GRAPHNAME, railsGraph);
        } catch (IOException ex) {
            log.error("save graph failed", ex);
        }

    }

    public void loadGraph() {
        FileInputStream fos = null;
        try {
            fos = new FileInputStream(GRAPHNAME);
            ObjectInputStream oos = new ObjectInputStream(fos);
            railsGraph = (Graph) oos.readObject();
            fos.close();
        } catch (ClassNotFoundException ex) {
            log.error("graph file not exist", ex);
        } catch (IOException ex) {
            log.error("io errors", ex);
        }
    }

    public Graph<String, DefaultEdge> getRailsGraph() {
        return railsGraph;
    }

    public boolean checkExist() {
        File file = new File(GRAPHNAME);
        if (file.exists()) {
            return true;
        }
        return false;
    }
}
